//导入React和路由依赖
import React from 'react';
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom';
import { useQuery, gql } from '@apollo/client';
//导入共用的布局组件
import Layout from '../components/Layout';

//导入路由
import Home from './home';
import MyNotes from './mynotes';
import Favorites from './favorites';
import NotePage from './note';
import SignUp from './signup';
import SignIn from './signin';
import NewNote from './new';
import EditNote from './edit';
import { IS_LOGGED_IN } from '../gql/query';


const PrivateRoute = ({ component: Component, ...rest }) => {
    const { loading, error, data } = useQuery(IS_LOGGED_IN);
    if (loading) {
        return <p>Loading...</p>;
    }
    if (error) {
        return <p>Error!</p>
    }
    return(
        <Route
            {...rest}
            render={props =>
            data.isLoggedIn === true? (
                <Component {...props} />
            ) : (
                <Redirect 
                    to={{
                        pathname: '/signin',
                        state: { from:props.location }
                    }}
                />
            )
        }
        />
    );
};

const Pages = () => {
    return(
        <Router>
            <Layout>
                <Route exact path="/" component={Home}></Route>
                <PrivateRoute path="/mynotes" component={MyNotes}></PrivateRoute>
                <PrivateRoute path="/favorites" component={Favorites}></PrivateRoute>
                <Route path="/note/:id" component={NotePage}></Route>
                <Route path="/signup" component={SignUp}></Route>
                <Route path="/signin" component={SignIn}></Route>
                <PrivateRoute path="/new" component={NewNote}></PrivateRoute>
                <PrivateRoute path="/edit/:id" component={EditNote}></PrivateRoute>
            </Layout>
        </Router>
    )
};

export default Pages;